<template>
  <div class="p-6 space-y-4">
    <!-- 顶部装置/单元选择 + 检索栏 -->
    <el-card shadow="never" class="rounded-lg">
      <div class="flex flex-col gap-4">
        <div class="flex items-center gap-3">
          <el-select v-model="plant" placeholder="请选择装置" class="!w-60">
            <el-option v-for="p in plantOptions" :key="p" :label="p" :value="p" />
          </el-select>
          <el-radio-group v-model="unit">
            <el-radio-button v-for="u in unitOptions" :key="u" :label="u" />
          </el-radio-group>
        </div>
        <el-form :model="filters" label-position="top" class="search-form" @keyup.enter.native="handleQuery">
          <el-row :gutter="12" align="bottom">
            <el-col :span="4">
              <el-form-item label="工艺位号">
                <el-input v-model="filters.sysNum" placeholder="请输入" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="位号描述">
                <el-input v-model="filters.tagDescription" placeholder="请输入" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="控制系统">
                <el-select v-model="filters.controlSystem" placeholder="请选择" clearable>
                  <el-option v-for="(item, index) in controlSystemOptions" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="报警类型">
                <el-select v-model="filters.alarmType" placeholder="请选择" clearable>
                  <el-option v-for="(item, index) in alarmTypeOptions" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" class="flex justify-end items-end gap-2">
              <el-button type="primary" :loading="queryLoading" @click="handleQuery">
                <el-icon class="mr-1">
                  <Search />
                </el-icon>
                查询
              </el-button>
              <el-button :icon="Plus" @click="onCreate">新增</el-button>
              <el-button :icon="Upload">导入</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="rounded-lg">
      <el-table v-loading="tableLoading" :data="tableData">
        <el-table-column label="序号" type="index" width="80" align="center" :index="indexMethod" />
        <el-table-column prop="sysNum" label="工艺位号" min-width="160" />
        <el-table-column prop="tagDescription" label="位号描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="controlSystem" label="控制系统" min-width="140">
          <template #default="{ row }">
            {{ controlSystemKeyName[row?.controlSystem] || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="alarmType" label="报警类型" min-width="140">
          <template #default="{ row }">
            {{ alarmTypeKeyName[row?.alarmType] || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="indicatorTypeName" label="监测项" min-width="180" />
        <el-table-column label="操作" width="160" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="onView(row)">详情</el-button>
            <el-button link type="danger" @click="onDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗（按设计样式） -->
    <el-dialog v-model="detailVisible" width="860px" destroy-on-close>
      <template #header>
        <div class="flex items-center justify-between pr-10">
          <div class="flex items-center gap-2">
            <div class="w-1 h-6 bg-#5B8FF9" />
            <div class="text-lg font-600">
              <template v-if="formOperationType === FormOperationTypeEnum.ADD"> 新增报警管理 </template>
              <template v-else>
                {{ detailRecord?.sysNum || '-' }}
              </template>
            </div>
          </div>
          <div>
            <el-button v-if="formOperationType !== FormOperationTypeEnum.ADD" type="primary" @click="onEdit">
              <svg-icon icon-class="edit-1"></svg-icon>
              编辑
            </el-button>
          </div>
        </div>
      </template>
      <el-form ref="formRef" :model="detailRecord" :rules="formRules" label-position="left" label-width="110px" class="w-full">
        <el-row :gutter="16" class="px-5">
          <el-col :span="12">
            <el-form-item label="采集器ID" prop="collectorId">
              <span v-if="viewForm">{{ detailRecord?.collectorId || '-' }}</span>
              <el-input v-else v-model="detailRecord.collectorId" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工艺位号" prop="sysNum">
              <span v-if="viewForm">{{ detailRecord?.sysNum || '-' }}</span>
              <el-input v-else v-model="detailRecord.sysNum" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="点位名称" prop="name">
              <span v-if="viewForm">{{ detailRecord?.name || '-' }}</span>
              <el-input v-else v-model="detailRecord.name" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监测项" prop="indicatorType">
              <span v-if="viewForm">{{ indicatorTypeKeyName[detailRecord?.indicatorType] || '-' }}</span>
              <el-select v-else v-model="detailRecord.indicatorType" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in indicatorTypeOptions" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高报阈值" prop="highAlarm">
              <span v-if="viewForm">{{ detailRecord?.highAlarm ?? '-' }}</span>
              <el-input v-else v-model.number="detailRecord.highAlarm" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高高报阈值" prop="highHighAlarm">
              <span v-if="viewForm">{{ detailRecord?.highHighAlarm ?? '-' }}</span>
              <el-input v-else v-model.number="detailRecord.highHighAlarm" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="低报阈值" prop="lowAlarm">
              <span v-if="viewForm">{{ detailRecord?.lowAlarm ?? '-' }}</span>
              <el-input v-else v-model.number="detailRecord.lowAlarm" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="低低报阈值" prop="lowLowAlarm">
              <span v-if="viewForm">{{ detailRecord?.lowLowAlarm ?? '-' }}</span>
              <el-input v-else v-model.number="detailRecord.lowLowAlarm" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仪表上限" prop="rangeTop">
              <span v-if="viewForm">{{ detailRecord?.rangeTop ?? '-' }}</span>
              <el-input v-else v-model.number="detailRecord.rangeTop" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仪表下限" prop="rangeBottom">
              <span v-if="viewForm">{{ detailRecord?.rangeBottom ?? '-' }}</span>
              <el-input v-else v-model.number="detailRecord.rangeBottom" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属控制系统" prop="controlSystem">
              <span v-if="viewForm">{{ controlSystemKeyName[detailRecord?.controlSystem] || '-' }}</span>
              <el-select v-else v-model="detailRecord.controlSystem" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in controlSystemOptions" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警类型" prop="alarmType">
              <span v-if="viewForm">{{ alarmTypeKeyName[detailRecord?.alarmType] || '-' }}</span>
              <el-select v-else v-model="detailRecord.alarmType" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in alarmTypeOptions" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="位号描述" prop="tagDescription">
              <div v-if="viewForm" class="whitespace-pre-wrap">{{ detailRecord?.tagDescription || '-' }}</div>
              <el-input v-else v-model="detailRecord.tagDescription" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="flex justify-center gap-2">
          <el-button @click="detailVisible = false">
            <el-icon class="mr-1">
              <Close />
            </el-icon>
            退出
          </el-button>
          <el-button type="primary" @click="onSave" v-if="formOperationType !== FormOperationTypeEnum.INFO">
            <el-icon class="mr-1">
              <Check />
            </el-icon>
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="AlarmManagement">
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { Check, Close, Plus, Search, Upload } from '@element-plus/icons-vue';
import { addIndicator, delIndicator, getIndicatorTypeList, listIndicator, updateIndicator } from '@/api/system/indicator';
import { IndicatorForm, IndicatorQuery, IndicatorVO } from '@/api/system/indicator/types';
import { FormOperationTypeEnum } from '@/enums';

const plantOptions = ['甲醇制氢装置', '环氧乙烷装置', '醋酸装置'];
const plant = ref(plantOptions[0]);
const allUnitOptions: Record<string, string[]> = {
  甲醇制氢装置: ['丁醇精馏塔', '环氧乙烷精馏塔', '丁醇预精馏塔'],
  环氧乙烷装置: ['EO精馏塔', 'EO吸收塔'],
  醋酸装置: ['反应塔', '精制塔']
};
const unit = ref('丁醇精馏塔');
const unitOptions = computed(() => allUnitOptions[plant.value] || []);

const formOperationType = ref(FormOperationTypeEnum.ADD);

const viewForm = computed(() => formOperationType.value === FormOperationTypeEnum.INFO);

const controlSystemKeyName = {
  1: 'DCS',
  2: 'SIS',
  3: 'GDS',
  4: '控制回路',
  5: 'MES'
};

const controlSystemOptions = [
  {
    label: 'DCS',
    value: 1
  },
  {
    label: 'SIS',
    value: 2
  },
  {
    label: 'GDS',
    value: 3
  },
  {
    label: '控制回路',
    value: 4
  },
  {
    label: 'MES',
    value: 5
  }
];

const alarmTypeKeyName = {
  1: 'A类报警',
  2: 'B类报警',
  3: '一级报警',
  4: '二级报警'
};

const alarmTypeOptions = [
  {
    label: 'A类报警',
    value: 1
  },
  {
    label: 'B类报警',
    value: 2
  },
  {
    label: '一级报警',
    value: 3
  },
  {
    label: '二级报警',
    value: 4
  }
];

// 搜索条件
const filters = reactive({
  sysNum: '',
  tagDescription: '',
  controlSystem: '',
  alarmType: ''
});

// 表格
const tableLoading = ref(false);
const queryLoading = ref(false);
const tableData = ref<IndicatorVO[]>([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const indexMethod = (index: number) => (pagination.currentPage - 1) * pagination.pageSize + index + 1;

const handleQuery = () => {
  queryLoading.value = true;
  tableLoading.value = true;
  const params: IndicatorQuery = {
    ...filters,
    pageSize: pagination.pageSize,
    pageNum: pagination.currentPage
  };
  listIndicator(params)
    .then((res) => {
      if (res.rows && res.rows?.length > 0) {
        tableData.value = res.rows;
        pagination.total = res?.total;
      } else {
        tableData.value = [];
      }
    })
    .catch((e) => {
      tableData.value = [];
      console.error(e);
    })
    .finally(() => {
      queryLoading.value = false;
      tableLoading.value = false;
    });
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  handleQuery();
};
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  handleQuery();
};

// 详情弹窗
const detailVisible = ref(false);

const baseForm: IndicatorForm = {
  id: undefined,
  /** 采集器id */
  collectorId: undefined,
  /** 系统位号 */
  sysNum: undefined,
  /** 点位名称(必填) */
  name: undefined,
  /** 监测项(必填) */
  indicatorType: undefined,
  /** 高报阈值 */
  highAlarm: undefined,
  /** 高高报阈值 */
  highHighAlarm: undefined,
  /** 低报阈值 */
  lowAlarm: undefined,
  /** 低低报阈值 */
  lowLowAlarm: undefined,
  /** 仪表上限(必填) */
  rangeTop: undefined,
  /** 仪表下限(必填) */
  rangeBottom: undefined,
  /** 所属控制系统 1：DCS 2：SIS 3：GDS 4：控制回路 5：MES */
  controlSystem: undefined,
  /** 报警类型 1：A类报警 2：B类报警 3：一级报警 4：二级报警 */
  alarmType: undefined,
  /** 位号描述 */
  tagDescription: undefined
};
const formRef = ref<FormInstance>();
const detailRecord = ref<IndicatorForm>({ ...baseForm });
interface RuleForm {
  name: string;
  indicatorType: string;
  rangeTop: string;
  rangeBottom: string;
}
const formRules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: '请输入', trigger: 'blur' }],
  indicatorType: [{ required: true, message: '请选择', trigger: 'change' }],
  rangeTop: [{ required: true, message: '请输入', trigger: 'blur' }],
  rangeBottom: [{ required: true, message: '请输入', trigger: 'blur' }]
});

const onView = (row: IndicatorForm) => {
  formOperationType.value = FormOperationTypeEnum.INFO;
  restForm();
  detailRecord.value = { ...row };
  detailVisible.value = true;
};
const onEdit = () => {
  formOperationType.value = FormOperationTypeEnum.EDIT;
};
const onDelete = (row: IndicatorForm) => {
  ElMessageBox.confirm('确认删除该记录？', '提示', { type: 'warning' }).then(() => {
    delIndicator(row.id).then(() => {
      handleQuery();
      ElMessage.success('删除成功');
    });
  });
};
const onCreate = () => {
  formOperationType.value = FormOperationTypeEnum.ADD;
  restForm();
  detailVisible.value = true;
};
const restForm = () => {
  detailRecord.value = { ...baseForm };
};

const onSave = () => {
  formRef.value.validate((valid, _fields) => {
    if (valid) {
      if (formOperationType.value === FormOperationTypeEnum.EDIT && detailRecord.value?.id) {
        updateIndicator(detailRecord.value)
          .then((_res) => {
            ElMessage.success('保存成功');
            detailVisible.value = false;
          })
          .catch((e) => {
            console.error(e);
          })
          .finally(() => {
            handleQuery();
          });
      } else {
        addIndicator(detailRecord.value)
          .then((_res) => {
            ElMessage.success('保存成功');
            detailVisible.value = false;
          })
          .catch((e) => {
            console.error(e);
          })
          .finally(() => {
            handleQuery();
          });
      }
    }
  });
};

const indicatorTypeOptions = ref([]);
const indicatorTypeKeyName = ref({});
const getIndicatorTypeListInfo = async () => {
  const res = await getIndicatorTypeList();
  if (res.data) {
    const array = [];
    const obj = [];
    Object.keys(res.data).forEach((key) => {
      const label = res.data[key];
      array.push({
        label: label,
        value: key
      });
      obj[key] = label;
    });
    indicatorTypeOptions.value = array;
    indicatorTypeKeyName.value = obj;
  } else {
    indicatorTypeOptions.value = [];
    indicatorTypeKeyName.value = {};
  }
};

onMounted(async () => {
  await getIndicatorTypeListInfo();
  handleQuery();
});
</script>

<style scoped>
/* 无需自定义样式，保留作用域块避免污染 */
</style>
